import os
import random
import time
from datetime import datetime, timedelta
from typing import List

from selenium.webdriver import Keys
from selenium.webdriver.common.by import By

from Case.python_ui.Common.basepage import Basepage
from Case.python_ui.PageLocate.admin_order_mng_locator import AdminOrderMngLocator
from Case.python_ui.Test_data.menu_name_data import MenuName
from Case.python_ui.Common.excel import excel


class AdminOrderMngPages(Basepage):
    query_param = {
        "email": "Etest0302@sigma.com",
        "product": "Web Application Firewall",
        "instanceId": "waf-1645",
        "start_time": "01-02-2024",
        "end_time": "29-02-2024",

        "orders": {
            "type": ["Personal/Enterprise", "Business Partner", "Technology", "Reseller Account"]
        }
    }

    usage_query_table_cols = ['Account Email', 'Product', 'Region', 'Instance ID', 'Usage Billing Item',
                              'Consumption Start Time', 'Consumption End Time', 'Usage', 'Usage Unit']

    assert_data = {
        "pup_text": {
            "download_success": "Create asynchronous task successfully"
        },
        "export_records_url": "/console/exportRecords",
        "order_detail_url": "/console/orderManagement/order/orderDetail",
        "file_name": "UsageQuery",
        "orders_file_name": "Orders"
    }

    def enter_usage_query(self):
        doc = "进入Tickets Report页面"
        self.wait_elevisble(AdminOrderMngLocator.dashboard_tab, doc)
        self.click_element(AdminOrderMngLocator.dashboard_tab, doc)
        time.sleep(1)
        self.wait_elevisble(AdminOrderMngLocator.bill_tab, doc)
        self.click_element(AdminOrderMngLocator.bill_tab, doc)
        time.sleep(1)
        self.wait_elevisble(AdminOrderMngLocator.ticket_tab, doc)
        self.click_element(AdminOrderMngLocator.ticket_tab, doc)
        time.sleep(1)
        self.wait_elevisble(AdminOrderMngLocator.usage_query_tab, doc)
        self.click_element(AdminOrderMngLocator.usage_query_tab, doc)
        time.sleep(3)

    def enter_orders(self):
        doc = "进入Tickets Report页面"
        self.wait_elevisble(AdminOrderMngLocator.dashboard_tab, doc)
        self.click_element(AdminOrderMngLocator.dashboard_tab, doc)
        time.sleep(1)
        self.wait_elevisble(AdminOrderMngLocator.bill_tab, doc)
        self.click_element(AdminOrderMngLocator.bill_tab, doc)
        time.sleep(1)
        self.wait_elevisble(AdminOrderMngLocator.ticket_tab, doc)
        self.click_element(AdminOrderMngLocator.ticket_tab, doc)
        time.sleep(1)
        self.wait_elevisble(AdminOrderMngLocator.orders_tab, doc)
        self.click_element(AdminOrderMngLocator.orders_tab, doc)
        time.sleep(3)

    def check_usage_query_default(self):
        doc = "查看Usage Query菜单的默认数据"
        self.enter_usage_query()

        assert self.get_element(AdminOrderMngLocator.empty_description, doc)

    def query_usage_query(self):
        doc = "查询Usage Query列表"
        self.enter_usage_query()

        self.send_keys(AdminOrderMngLocator.email_input, self.query_param['email'], doc)
        time.sleep(1)
        self.move_mouse_to_click_element(AdminOrderMngLocator.email_option, doc)
        time.sleep(1)
        self.send_keys(AdminOrderMngLocator.product_input, self.query_param['product'], doc)
        time.sleep(1)
        product_option_xpath = "//div[contains(@title, '${opt_name}')]"
        self.driver.find_element(By.XPATH,
                                 product_option_xpath.replace("${opt_name}", self.query_param['product'])).click()
        time.sleep(1)
        self.send_keys(AdminOrderMngLocator.instance_id_input, self.query_param['instanceId'], doc)

        # 去除时间选择器的readonly属性
        js1 = "document.getElementById('date').removeAttribute('readonly')"
        self.excute_js(js1)
        js2 = "document.querySelector('input[readonly]').removeAttribute('readonly')"
        self.excute_js(js2)

        # 输入起止时间查询
        self.send_keys(AdminOrderMngLocator.start_time_input, self.query_param['start_time'], doc)
        time.sleep(1)

        start_time_option_xpath = "//td[@title='${opt_value}' and contains(@class, 'view')]"
        start_time_list = self.query_param['start_time'].split('-')
        start_time_list.reverse()
        self.click_by_js((By.XPATH, start_time_option_xpath.replace("${opt_value}", '-'.join(start_time_list))), doc)
        time.sleep(1)

        self.send_keys(AdminOrderMngLocator.end_time_input, self.query_param['end_time'], doc)

        time.sleep(1)

        end_time_option_xpath = "//td[@title='${opt_value}' and contains(@class, 'view')]"
        end_time_list = self.query_param['end_time'].split('-')
        end_time_list.reverse()
        self.click_by_js((By.XPATH, end_time_option_xpath.replace("${opt_value}", '-'.join(end_time_list))), doc)

        time.sleep(1)
        self.click_element(AdminOrderMngLocator.search_button, doc)
        time.sleep(3)

        data_rows = self.get_elements(AdminOrderMngLocator.data_rows, doc)
        for data in data_rows:
            items = data.find_elements(By.XPATH, ".//td")
            assert self.query_param['email'] in items[0].text
            assert self.query_param['product'] in items[1].text
            assert self.query_param['instanceId'] in items[3].text
            start_date_reverse = self.reverse_date(self.query_param['start_time'])
            end_date_reverse = self.reverse_date(self.query_param['end_time'])
            assert datetime.strptime(self.reverse_date(items[5].text[0:10]), "%Y-%m-%d") >= datetime.strptime(
                start_date_reverse, "%Y-%m-%d")
            # assert datetime.strptime(self.reverse_date(items[6].text[0:10]), "%Y-%m-%d") <= datetime.strptime(
            #     end_date_reverse, "%Y-%m-%d") + timedelta(days=1)

    def reverse_date(self, date_str):
        data_str_list = date_str.split('-')
        data_str_list.reverse()
        return '-'.join(data_str_list)

    def check_usage_query_cols(self):
        doc = "查看Usage Query列表字段"
        self.enter_usage_query()

        table_cols = self.get_elements(AdminOrderMngLocator.table_columns, doc)
        assert table_cols[0].text == self.usage_query_table_cols[0]
        assert table_cols[1].text == self.usage_query_table_cols[1]
        assert table_cols[2].text == self.usage_query_table_cols[2]
        assert table_cols[3].text == self.usage_query_table_cols[3]
        assert table_cols[4].text == self.usage_query_table_cols[4]
        assert table_cols[5].text.startswith(self.usage_query_table_cols[5])
        assert table_cols[6].text.startswith(self.usage_query_table_cols[6])
        assert table_cols[7].text == self.usage_query_table_cols[7]
        assert table_cols[8].text == self.usage_query_table_cols[8]

    def download_usage_query(self, cmdopt):
        doc = "下载Usage Query数据"
        self.query_usage_query()

        self.click_element(AdminOrderMngLocator.download_button, doc)

        self.wait_elevisble(AdminOrderMngLocator.success_pup, doc)
        assert self.get_element(AdminOrderMngLocator.success_pup, doc).text == self.assert_data["pup_text"][
            "download_success"]

        time.sleep(3)

        assert self.driver.current_url.endswith(self.assert_data["export_records_url"])

        self.wait_eleinvisble(AdminOrderMngLocator.export_records_download_buttons_disabled, doc)

        time.sleep(2)

        self.get_elements(AdminOrderMngLocator.export_records_download_buttons, doc)[0].click()
        time.sleep(3)

        list_of_files = os.listdir(MenuName.download_path[cmdopt])
        latest_file = list_of_files[-1]
        last_file_path = os.path.abspath(latest_file)
        time.sleep(2)
        print(latest_file)
        print(last_file_path)
        assert latest_file.startswith(self.assert_data['file_name']) and latest_file.endswith(".xlsx")

    def check_order_detail(self):
        doc = "查看order detail"
        self.enter_orders()

        order_id = self.get_element(AdminOrderMngLocator.orders_order_id, doc).text
        # 由order id进入details页面
        self.click_element(AdminOrderMngLocator.orders_order_id, doc)

        time.sleep(2)
        assert self.assert_data["order_detail_url"] in self.driver.current_url

        assert self.get_element(AdminOrderMngLocator.order_detail_title, doc).text == order_id

        self.click_element(AdminOrderMngLocator.order_detail_back, doc)
        time.sleep(3)
        # 由view detail进入details页面
        self.click_element(AdminOrderMngLocator.orders_view_detail, doc)
        time.sleep(2)
        assert self.get_element(AdminOrderMngLocator.order_detail_title, doc).text == order_id

    def orders_check_download_orders(self, cmdopt):
        for custType in self.query_param['orders']['type']:
            self.enter_orders()
            self.download_orders(cmdopt, custType, True)
            self.refresh_page()

    def download_orders(self, cmdopt, custType, if_assert: bool = False):

        doc = "下载orders"
        self.send_keys(AdminOrderMngLocator.orders_custType_input, custType, doc)
        time.sleep(1)
        custType_option_xpath = "//div[contains(@title, '${opt_name}')]"
        self.driver.find_element(By.XPATH,
                                 custType_option_xpath.replace("${opt_name}", custType)).click()
        time.sleep(2)
        # 去除时间选择器的readonly属性
        js1 = "document.getElementById('date').removeAttribute('readonly')"
        self.excute_js(js1)
        js2 = "document.querySelector('input[readonly]').removeAttribute('readonly')"
        self.excute_js(js2)

        # 输入起止时间查询
        self.send_keys(AdminOrderMngLocator.start_time_input, self.query_param['start_time'], doc)
        time.sleep(1)

        start_time_option_xpath = "//td[@title='${opt_value}' and contains(@class, 'view')]"
        start_time_list = self.query_param['start_time'].split('-')
        start_time_list.reverse()
        self.click_by_js((By.XPATH, start_time_option_xpath.replace("${opt_value}", '-'.join(start_time_list))), doc)
        time.sleep(1)

        self.send_keys(AdminOrderMngLocator.orders_end_time_input, self.query_param['end_time'], doc)

        time.sleep(1)

        end_time_option_xpath = "//td[@title='${opt_value}' and contains(@class, 'view')]"
        end_time_list = self.query_param['end_time'].split('-')
        end_time_list.reverse()
        self.click_by_js((By.XPATH, end_time_option_xpath.replace("${opt_value}", '-'.join(end_time_list))), doc)

        time.sleep(3)

        # 点击下载
        self.click_element(AdminOrderMngLocator.download_button, doc)

        self.wait_elevisble(AdminOrderMngLocator.success_pup, doc)
        assert self.get_element(AdminOrderMngLocator.success_pup, doc).text == self.assert_data["pup_text"][
            "download_success"]

        time.sleep(3)

        assert self.driver.current_url.endswith(self.assert_data["export_records_url"])

        # 是否下载文件并判断文件名称
        if if_assert:
            time.sleep(10)
            self.get_elements(AdminOrderMngLocator.export_records_download_buttons, doc)[0].click()
            time.sleep(3)

            list_of_files = os.listdir(MenuName.download_path[cmdopt])
            latest_file = list_of_files[-1]
            last_file_path = os.path.abspath(latest_file)
            time.sleep(2)
            assert latest_file.startswith(self.assert_data['orders_file_name']) and latest_file.endswith(".xlsx")

    def orders_download_route(self, cmdopt):
        doc = "校验Orders下载页面跳转"
        column_title_list = ["File Name", "Module", "Status", "Creation Time", "Actions"]
        self.enter_orders()
        self.download_orders(cmdopt, "Personal/Enterprise")
        table_columns = self.get_elements(AdminOrderMngLocator.export_records_table_columns, doc)
        for column in table_columns:
            assert column.text == column_title_list[table_columns.index(column)]

    def check_export_records_status(self, cmdopt):
        doc = "校验Export Records页面Status变化"
        self.enter_orders()
        self.download_orders(cmdopt, "Personal/Enterprise")

        assert self.get_elements(AdminOrderMngLocator.export_records_status, doc)[0].text == "Being Generated"
        time.sleep(10)
        assert self.get_elements(AdminOrderMngLocator.export_records_status, doc)[0].text == "Export successful"


    def enter_export_records(self):
        doc = "进入Export Records页面"
        js_object = 'document.getElementsByClassName("cre-sider-menu cre-sider-menu-open")[0].scrollTop=10000'
        self.excute_js(js_object)
        time.sleep(2)
        self.click_element(AdminOrderMngLocator.export_records_tab, doc)
        time.sleep(5)


    def filter_export_records(self, options: List, if_reset: bool = False, if_assert: bool = False, if_refresh: bool = False):
        doc = "通过Status筛选Export Record"
        self.click_element(AdminOrderMngLocator.export_records_status_filter, doc)
        time.sleep(1)
        filter_items = self.get_elements(AdminOrderMngLocator.export_records_status_filter_item, doc)
        for option in options:
            time.sleep(1)
            if option == "Export successful":
                filter_items[0].click()
            elif option == "Being Generated":
                filter_items[1].click()
            elif option == "Export failed":
                filter_items[2].click()
            elif option == "File is expired":
                filter_items[3].click()
        time.sleep(1)

        if if_reset:
            self.click_element(AdminOrderMngLocator.export_records_status_filter_reset_button, doc)
        self.click_element(AdminOrderMngLocator.export_records_status_filter_confirm_button, doc)

        if if_assert:
            time.sleep(5)
            table_rows = self.get_elements(AdminOrderMngLocator.export_records_status, doc)
            for item in table_rows:
                assert item.text in options

        if if_refresh:
            self.refresh_page()
            time.sleep(5)

    filter_items = ["Export successful", "Being Generated", "Export failed", "File is expired"]

    def export_records_status_filter(self):
        doc = "校验Export Records页面Status筛选"

        self.enter_export_records()

        self.filter_export_records([self.filter_items[0]], if_assert=True, if_refresh=True)
        self.filter_export_records([self.filter_items[1]], if_assert=True, if_refresh=True)
        self.filter_export_records([self.filter_items[2]], if_assert=True, if_refresh=True)
        self.filter_export_records([self.filter_items[3]], if_assert=True, if_refresh=True)
        self.filter_export_records([self.filter_items[0], self.filter_items[1]], if_assert=True, if_refresh=True)
        self.filter_export_records([self.filter_items[0], self.filter_items[1], self.filter_items[2]], if_assert=True, if_refresh=True)
        self.filter_export_records(self.filter_items, if_assert=True)


    def export_records_download_restraint(self):
        doc = "校验Export Records页面Status对Download的约束"
        self.enter_export_records()

        self.filter_export_records([self.filter_items[0]], if_assert=True)
        download_buttons = self.get_elements(AdminOrderMngLocator.export_records_download, doc)
        for btn in download_buttons:
            print(btn.get_attribute("disabled"))
            assert btn.get_attribute("disabled") is None

        self.refresh_page()
        time.sleep(5)

        self.filter_export_records([item for item in self.filter_items if item != 'Export successful'], if_assert=True)
        time.sleep(3)
        download_buttons = self.get_elements(AdminOrderMngLocator.export_records_download, doc)
        for btn in download_buttons:
            print(btn.get_attribute("disabled"))
            assert btn.get_attribute("disabled") == "true"



